# users/models.py

from django.db import models
from django.contrib.auth.models import AbstractUser
from django.core.exceptions import ValidationError
from datetime import timedelta
import random
import string
from django.utils import timezone

def user_avatar_path(instance, filename):
    return f'avatars/user_{instance.user.id}/{filename}'

def generate_verification_code(length=6):
    return ''.join(random.choices(string.ascii_letters + string.digits, k=length))

class User(AbstractUser):
    email = models.EmailField(unique=True)
    is_verified = models.BooleanField(default=False)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username']

    DISALLOWED_USERNAMES = ['admin', 'superuser', 'root']  # 根据需要添加更多

    def clean(self):
        super().clean()
        if self.username.lower() in User.DISALLOWED_USERNAMES:
            raise ValidationError({'username': '该用户名不允许使用。'})

class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')
    daily_check_in = models.IntegerField(default=0)
    consecutive_login_days = models.IntegerField(default=0)
    last_login_date = models.DateField(null=True, blank=True)
    avatar = models.ImageField(upload_to=user_avatar_path, null=True, blank=True)
    is_avatar_approved = models.BooleanField(default=False)

    def __str__(self):
        return f"{self.user.username} 的个人资料"

class DailyActivity(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='daily_activities')
    date = models.DateField()
    words_learned = models.IntegerField(default=0)
    is_logged_in = models.BooleanField(default=False)
    is_words_learned = models.BooleanField(default=False)

    class Meta:
        unique_together = ('user', 'date')

    def __str__(self):
        return f"{self.user.username} - {self.date}"


def generate_verification_code(length=6):
    return ''.join(random.choices(string.ascii_letters + string.digits, k=length))

class EmailVerification(models.Model):
    email = models.EmailField(unique=True)
    code = models.CharField(max_length=6, default=generate_verification_code)
    created_at = models.DateTimeField(auto_now_add=True)

    def is_expired(self):
        return timezone.now() > self.created_at + timedelta(minutes=10)  # 验证码有效期为10分钟

    def expires_at(self):
        return self.created_at + timedelta(minutes=10)
    expires_at.short_description = 'Expires At'  # 为管理员界面中的列设置名称

    def __str__(self):
        return f"{self.email} - {self.code}"

class Avatar(models.Model):
    image = models.ImageField(upload_to='predefined_avatars/')
    name = models.CharField(max_length=50)

    def __str__(self):
        return self.name
